package com.app.reptile.tasks;

import com.app.reptile.base.SchedulerSingleton;
import com.app.reptile.constant.JobAnnotation;
import com.mybatis.mapper.SysConfigMapper;
import com.mybatis.pojo.SysConfig;
import org.quartz.*;

import java.util.List;

/*
每分钟执行一次
 */
@JobAnnotation("* * * * * ? *")
public class JobService extends AbstractTask{

    private SysConfigMapper sysConfigMapper;

    public SysConfigMapper getSysConfigMapper() {
        return sysConfigMapper;
    }

    public void setSysConfigMapper(SysConfigMapper sysConfigMapper) {
        this.sysConfigMapper = sysConfigMapper;
    }

    @Override
    protected void start() throws Exception {
        List<SysConfig> list = sysConfigMapper.selectListByType("job");
        Scheduler scheduler = SchedulerSingleton.getInstance();
        for(SysConfig sysConfig : list){
            JobKey jobKey = new JobKey(sysConfig.getName(),sysConfig.getType());
            boolean flag = scheduler.checkExists(jobKey);
            TriggerKey triggerKey = new TriggerKey(jobKey.getName(),jobKey.getGroup());
            Trigger.TriggerState state = scheduler.getTriggerState(triggerKey);
            if (flag){
                if (sysConfig.getDelFlag()){
                    scheduler.deleteJob(jobKey);
                }
                if (sysConfig.getIsDisable()){
                    scheduler.pauseJob(jobKey);//暂停任务
                }else{
                    if (state == Trigger.TriggerState.PAUSED){
                        scheduler.resumeJob(jobKey);//恢复任务
                    }
                }


                if ("立即执行".equals(sysConfig.getMark())){
                    sysConfig.setMark("执行中");
                    sysConfigMapper.updateSysConfig(sysConfig);
                    scheduler.triggerJob(jobKey);
                }


            }else{
                if (!sysConfig.getDelFlag() && !sysConfig.getIsDisable()) {
                    try{
                        Class<? extends Job> jobClazz = (Class<? extends Job>) Class.forName(sysConfig.getName());
                        JobDetail job = JobBuilder.newJob(jobClazz).withIdentity(jobKey).build();
                        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                                .withSchedule(CronScheduleBuilder.cronSchedule(sysConfig.getValue())).startNow().build();
                        scheduler.scheduleJob(job, trigger);
                    }catch (Exception e){
                        logger.error("fail load class", e);
                    }
                }
            }
        }
    }

}
